package com.kevin.Code.BFS;

import com.kevin.Code.Tree.TreeNode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author Vinlee Xiao
 * @Classname MinimumDepthofBinaryTree
 * @Description Leetcode 111 二叉树的最小深度  简单题 bfs
 * @Date 2021/9/23 16:02
 * @Version 1.0
 */
public class MinimumDepthofBinaryTree {


    public int minDepth(TreeNode root) {

        if (root == null) {
            return 0;
        }

        if (root.left == null && root.right == null) {
            return 1;
        }
        int i = bfs(root);
        return i;
    }


    /**
     * @param root
     * @return
     */
    public int bfs(TreeNode root) {

        Deque<TreeNode> queue = new LinkedList<>();
        queue.addLast(root);

        int depth = 1;

        while (!queue.isEmpty()) {

            int size = queue.size();

            for (int i = 0; i < size; i++) {

                TreeNode node = queue.pollFirst();

                //达到叶子结点返回
                if (node.left == null && node.right == null) {
                    return depth;
                }

                if (node.left != null) {
                    queue.addLast(node.left);

                }

                if (node.right != null) {
                    queue.addLast(node.right);

                }

            }
            depth++;
        }

        return depth;
    }
}
